﻿using Core.Container;
using Core.Interface;
using Core.Log;
using Core.MessageEvent;
using Prism.Events;
using Prism.Ioc;
using ProcessControl.ViewModels;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace ProcessControl
{
    public class AutoProcess : IAutoProcess
    {
        CancellationTokenSource token;
        IContainerExtension Container;
        Container<ModBusDevice> container;         
        ManualResetEvent manual;
        Notify notifyErr, notifyAuto, notifyIni;
        HomePageViewModel homePage;
        IEventAggregator _ea;
        ICSVDataHelper _csv;
        ModBusDevice modBusDevice;
        //List<Task> listTask = new List<Task>(); 

        public AutoProcess(IEventAggregator ea)
        {
            _ea = ea;
            manual = new ManualResetEvent(true);
            Container = ContainerLocator.Current;
            container = Container.Resolve<Container<ModBusDevice>>("ModBusDevice");
            modBusDevice = container.Get("A");
            homePage = Container.Resolve<HomePageViewModel>();
            _csv = Container.Resolve<ICSVDataHelper>("CSV");       
            notifyErr = NotifyCollect.NotifyContainer["Error"];
            notifyAuto = NotifyCollect.NotifyContainer["Auto"];
            notifyIni= NotifyCollect.NotifyContainer["Initialization"];
        }

        private void ExecuteMainTask()
        {
            while (!token.IsCancellationRequested)
            {
                if (ExecutionCondition())
                {
                    #region
                    //listTask.Add(Task.Run(Task1, token.Token));                
                    //listTask.Add(Task.Run(Task2, token.Token));
                    //Task.WaitAll(listTask.ToArray(), 6000);//等待所有的线程完成后才会往下执行
                    //notifyAuto.Add("两个线程执行完成------------");
                    //Thread.Sleep(50);
                    #endregion
                    Task1();
                }
            }
        }

        private bool ExecutionCondition()
        {
            //modBusDevice.ReadRegister(0, out ushort value);
            //return (value == 11);
            return true;
        }

        ulong count = 0;
        private void Task1()
        {
            try
            {
                manual.WaitOne();
                //需要给我一个启动信号告诉我什么时候开始读取
                modBusDevice.ReadRegister(400, 1, out ushort[] values);
                //modBusDevice.WriteRegister(400,0);
                Point point = new Point(0, 0)
                {
                    X = count + 1,
                    Y = values[0]
                };
                count++;
                homePage.Add(point);
                //发布事件:发送总点数到UI界面实现平移
                _ea.GetEvent<ChartPlotterEvent>().Publish(count);
                _csv.Save(DateTime.Now.ToString("HH: mm:ss") +","+point.Y.ToString());
                notifyAuto.Add("任务1正在执行"+ Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(100);
            }
            catch (Exception ex)
            {
                notifyErr.Add(ex.ToString());
            }
        }

        public void Init()
        {
            try
            {          
                if (modBusDevice.Connect())
                { notifyIni.Add("PLC连接成功!"); }
                notifyIni.Add("整机初始化完成");
            }
            catch (Exception ex)
            {
                notifyErr.Add(ex.ToString());
            }
        }

        public void Pause()
        {
            manual.Reset();
        }

        public void Continue()
        {
            manual.Set();
        }

        public void Start()
        {
            token = new CancellationTokenSource();
            Task.Run(() => ExecuteMainTask());
        }

        public void Stop()
        {
            token.Cancel();
        }

        enum Step
        {
            取料1,
            移动,
            拍照,
            放料,
            放料1,
            放料2,
            放料3
        }

        private void Task2()
        {
            try
            {
                manual.WaitOne();
                notifyAuto.Add("任务2正在执行" + Thread.CurrentThread.ManagedThreadId);
            }
            catch (Exception ex)
            {
                notifyErr.Add(ex.ToString());
            }
        }
    }
}
